<?php
namespace app\v1\controller;
use support\Request;
use app\model\BillModel;
use app\model\BizPayRecordModel;
use app\model\BizGoodsTicketModel;
use app\model\BizAdminModel;
use app\model\UserModel;

class BillController {
    
    /**
     * 获取商家结算单列表
     * @param \support\Request $request
     * @return mixed
     */
    public function index(Request $request) {
        try {
            // 验证用户登录状态
            $user = $request->userLogin;
            if (!$user || empty($user['id'])) {
                throw new \Exception('用户未登录');
            }

            // 验证用户是否为商家管理员
            $bizAdmin = BizAdminModel::where('user_id', $user['id'])->first();
            if (!$bizAdmin) {
                throw new \Exception('您不是商家管理员');
            }

            $page = $request->get('page', 1);
            $pageSize = $request->get('pageSize', 10);

            // 获取该商家管理员管理的所有商家ID
            $bizIds = BizAdminModel::where('user_id', $user['id'])->pluck('biz_id')->toArray();
            if (empty($bizIds)) {
                throw new \Exception('您没有管理的商家');
            }

            // 查询结算单列表
            $query = BillModel::whereIn('biz_id', $bizIds);
            $total = $query->count();
            
            $bills = $query->orderBy('created_at', 'desc')
                          ->limit($pageSize)
                          ->offset(($page - 1) * $pageSize)
                          ->get();

            // 格式化数据
            foreach ($bills as &$bill) {
                $bill->created_at_formatted = date('Y-m-d H:i:s', $bill->created_at);
                $bill->day_formatted = $bill->day;
                $bill->status_text = $this->getStatusText($bill->status);
                $bill->money = round($bill->money, 2); // 格式化金额
            }

            return json([
                'data' => [
                    'list' => $bills,
                    'total' => $total,
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'hasMore' => ($page * $pageSize) < $total,
                    'bill_day' => config('site.bill_day')
                ],
                'msg' => '获取结算单列表成功',
                'code' => 1
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取结算单详情
     * @param \support\Request $request
     * @return mixed
     */
    public function detail(Request $request) {
        try {
            // 验证用户登录状态
            $user = $request->userLogin;
            if (!$user || empty($user['id'])) {
                throw new \Exception('用户未登录');
            }

            // 验证用户是否为商家管理员
            $bizAdmin = BizAdminModel::where('user_id', $user['id'])->first();
            if (!$bizAdmin) {
                throw new \Exception('您不是商家管理员');
            }

            $billId = $request->get('id');
            if (!$billId) {
                throw new \Exception('结算单ID不能为空');
            }

            // 获取该商家管理员管理的所有商家ID
            $bizIds = BizAdminModel::where('user_id', $user['id'])->pluck('biz_id')->toArray();
            if (empty($bizIds)) {
                throw new \Exception('您没有管理的商家');
            }

            // 查询结算单详情
            $bill = BillModel::where('id', $billId)
                           ->whereIn('biz_id', $bizIds)
                           ->first();
            if (!$bill) {
                throw new \Exception('结算单不存在或无权限查看');
            }

            // 获取结算单关联的支付记录
            $payRecords = BizPayRecordModel::where('bill_id', $billId)
                                         ->select([
                                             'id',
                                             'user_id',
                                             'pay_price',
                                             'pay_money',
                                             'pay_status',
                                             'paid_at',
                                             'score',
                                             'card_score',
                                             'discount',
                                             'created_at'
                                         ])
                                         ->get();

            // 获取结算单关联的核销码记录
            $tickets = BizGoodsTicketModel::where('bill_id', $billId)
                                        ->select([
                                            'id',
                                            'order_id',
                                            'goods_id',
                                            'goods_name',
                                            'phone',
                                            'status',
                                            'created_at'
                                        ])
                                        ->get();

            // 格式化数据
            $bill->created_at_formatted = date('Y-m-d H:i:s', $bill->created_at);
            $bill->day_formatted = $bill->day;
            $bill->status_text = $this->getStatusText($bill->status);
            $bill->money = round($bill->money, 2); // 格式化金额

            foreach ($payRecords as &$record) {
                $record->created_at_formatted = date('Y-m-d H:i:s', $record->created_at);
                $record->paid_at_formatted = $record->paid_at ? date('Y-m-d H:i:s', $record->paid_at) : '';
                $record->pay_status_text = $record->pay_status == 1 ? '已支付' : '未支付';
                $record->pay_price = round($record->pay_price, 2);
                $record->pay_money = round($record->pay_money, 2);
            }

            foreach ($tickets as &$ticket) {
                $ticket->created_at_formatted = date('Y-m-d H:i:s', $ticket->created_at);
                $ticket->status_text = $this->getTicketStatusText($ticket->status);
            }

            return json([
                'data' => [
                    'bill' => $bill,
                    'payRecords' => $payRecords,
                    'tickets' => $tickets,
                    'payRecordsCount' => $payRecords->count(),
                    'ticketsCount' => $tickets->count()
                ],
                'msg' => '获取结算单详情成功',
                'code' => 1
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 确认账单无误
     * @param \support\Request $request
     * @return mixed
     */
    public function confirm(Request $request) {
        try {
            // 验证用户登录状态
            $user = $request->userLogin;
            if (!$user || empty($user['id'])) {
                throw new \Exception('用户未登录');
            }

            $input = $request->post('data');
            $bill = BillModel::where('id', $input['id'])->first();
            $bill->status = 'checked';
            $bill->updated_at = time();
            $bill->save();

            return json([
                'data' => null,
                'msg' => '确认账单无误成功',
                'code' => 1
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取状态文本
     * @param string $status
     * @return string
     */
    private function getStatusText($status) {
        return BillModel::STATUS[$status];
    }

    /**
     * 获取核销码状态文本
     * @param int $status
     * @return string
     */
    private function getTicketStatusText($status) {
        switch ($status) {
            case 0:
                return '未使用';
            case 1:
                return '已使用';
            case 2:
                return '已过期';
            default:
                return '未知状态';
        }
    }
} 